简体   繁体   English

MySQL查询:涉及2个表

[英]mySQL query : involving 2 tables

I have two tables 我有两张桌子

table 1 : id, name, age, gender.
table 2(friend) : id1,id2. (stored only once i.e only one entry for a unique pair)

I need to write a query that takes an id and then return the result set containing the rows from table 1 corresponding to all his/hers friend. 我需要编写一个带有id的查询,然后返回包含表1中与他/她的所有朋友相对应的行的结果集。

I tried this Query 我试过这个查询

"SELECT * FROM table1 WHERE id IN ("
+ "(SELECT id2 FROM table2 WHERE (id1="+given_id+")) UNION "
+ "(SELECT id1 FROM table2 WHERE (id2="+given_id+")));"

but it does'nt seem to work says syntax error ... could anyone help me with this query. 但它似乎无法正常工作,说明语法错误...有人可以帮助我进行此查询。

Efforts appreciated ... Thanks a lot 感谢您的努力...非常感谢

You need to single quote given_id , because otherwise MySQL will think it is a column name. 您需要单引号given_id ,因为否则MySQL会认为它是列名。
This code will also work if given_id is a number. 如果given_id是数字,此代码也将起作用。

"SELECT t1.* "
+"FROM table1 t1 "
+"INNER JOIN table2 t2 ON (t1.id = t2.id1 OR t1.id = t2.id2) "
+"WHERE '"+given_id+"' IN (t2.id1, t1.id) "

Please use a join query: 请使用联接查询:

"SELECT `table1`.* FROM (`table1`) 
    LEFT OUTER JOIN `table2` ON 
        `table1`.`id` = `table2`.`id1`
    WHERE `table2`.`id2` =
    " + given_id;

You can narrow down your results by restricting conditions on a join. 您可以通过限制联接条件来缩小结果范围。 Since you will have to join your table2 on more than one id, you will have to join to it twice and alias the table names. 由于您将必须在多个id上加入table2,因此您将不得不两次加入它并为表名加上别名。

I believe something like this may do the trick: 我相信这样可以解决问题:

SELECT table1.*
FROM table1
JOIN table2 t2 ON table1.id = t2.id2
  AND t2.id1 = {given_id}
JOIN table2 t3 ON table1.id = t3.id1
  AND t3.id2 = {given_id};

您可以执行类似的操作。

SELECT * FROM table1 t1, table2 t2, WHERE t1.id = t2.id2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM