1个查询或2个单独的查询?

时间:2012-02-07 22:24:18

标签: php mysql

是否可以从两个完全相同的表中获取数据并打印出来?目前我能够在TABLE1中搜索,但也不能在TABLE2中搜索。

EDITTED

$name= $_SESSION['NAME'];

USER 
ID - NAME
1 - AAAA
2 - BBBB
3 - CCCC
4 - DDDD
5 - EEEE

TABLE1
ID - CODE - BUYSELL
1 -A - Buying
2 - A - Buying
3 - B Buying
4 - B - Selling
5 - C - Selling

 "SELECT * from TABLE1, TABLE2, USER WHERE '$person' = USER.NAME 
    AND TABLE1.ID = USER.ID"; 

TABLE2
ID - CODE - YESNO - CAR
1 - A - YES - VOLVO
2 - B - YES - FORD
3 - C - YES - M
4 - D - NO - BMW
5 - A - NO - VOLVO

(AND TABLE2.ID = USER.ID?????)

我希望所有人都搜索表1和表2?但添加TABLE2.ID = USER.ID基本上是在两个表中寻找相同的值。所以如果我想从table1和2中获得USERID 1的CODE。

是否可以在1个查询下或2个?

3 个答案:

答案 0 :(得分:2)

使用UNION将两个查询的结果合并为一个:

(SELECT id, name AS value, "users" AS tbl_name FROM users WHERE ...)
UNION
(SELECT id, code AS value, "codes" AS tbl_name FROM codes WHERE ...)

答案 1 :(得分:0)

假设您USER.ID与TABLE1.ID和TABLE2.ID相同,并且是相关的连接,那么我建议加入。

SELECT *
FROM `user` AS a 
JOIN `table1` AS b 
JOIN `table2` AS c 
ON a.id = b.id || a.id = c.id
WHERE (a.name = '".$person."') 
GROUP BY a.id

答案 2 :(得分:-1)

您可以使用MySQL JOIN

SELECT USER.NAME, TABLE1.ID AS `T1ID`, TABLE2.ID AS `T2ID`
FROM USER 
LEFT JOIN TABLE1 ON TABLE1.ID=USER.ID
LEFT JOIN TABLE2 ON TABLE2.ID=USER.ID