Wednesday 5 September 2018

MYSQL joins does not work as expected

I am trying to create a join statement to solve my problem but cannot get my head around it.

I am a new to join statements so please bear with me if my sql statement is nonsense.
I have two tables, one is a table of questions where users have asked questions about items for sale.
Second is a table of items that the user has asked a question about.
Table one called questions consists of question_ref, questioner_user_ref, item_ref, seller_ref, question_text, timestamp
questions
===========
+--------------+--------------------+---------+-----------+--------------+----------+
| question_ref |questioner_user_ref |item_ref |seller_ref |question_text |timestamp |
+--------------+--------------------+---------+-----------+--------------+----------+

Table two called my_item_comments consists of questioner_ref, item_ref, last_question_ref
my_item_comments
===========
+---------------+---------+------------------+
|questioner_ref |item_ref |last_question_ref |
+---------------+---------+------------------+

I have set up table two to keep track of items that the user has asked questions about so they can be informed when someone else asks the seller a question or the seller answers.
So I want to create a recordset of questions that a). Someone has answered a question about an item the user is selling b). A seller has replied to a question the user asked,
c). A third user has asked a question about an item that the user has also asked a question about.
A bit like facebook's commenting system, where you are informed about comments people have made on statuses that you have commented on.
So my current sql statement is as follows
$user_ref= current logged in user

  $sql=mysql_query("
    SELECT * FROM questions
    LEFT JOIN my_item_comments
    ON questions.item_ref=my_item_comments.item_ref
    WHERE questions.questioner_user_ref!='$user_ref'
    AND (questions.seller_ref='$user_ref' OR questions.item_ref=my_item_comments.item_ref
    ORDER BY timestamp DESC");

The results don't work and I think its because of the OR questions.item_ref=my_item_comments.item_ref but for the life of me I cannot work it out.
Any help would be greatly appreciated, even if it means restructuring my database with more tables or new fields in the tables.
thanks in advance, Barry

SELECT * FROM questions
LEFT JOIN my_item_comments ON questions.item_ref=my_item_comments.item_ref
WHERE
   questions.questioner_user_ref != '$user_ref' AND
   (questions.seller_ref='$user_ref' OR questions.item_ref=my_item_comments.item_ref)
ORDER BY timestamp DESC

I think you were missing a ) to enclose the OR clause (in the example above I added it)

0 comments:

Post a Comment