结合两个表的结果

时间:2014-01-02 11:16:28

标签: mysql sql select distinct union

我有两张桌子

TABLE_A
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| bid   | int(10) unsigned | NO   | PRI | 0       |       |
| uid   | int(10) unsigned | NO   | PRI | 0       |       |
+-------+------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

TABLE_B
+-------+------------------+------+-----+---------+-------+
| Field | Type             | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+-------+
| bid   | int(10) unsigned | NO   | PRI | 0       |       |
| uid   | int(10) unsigned | NO   | PRI | 0       |       |
+-------+------------------+------+-----+---------+-------+

我想在uid = 123时从两个表中选择出价; 注意:每个表有大约15个结果,有些表存在于两个表中,我需要进行区别选择。 所以我试过了:

SELECT DISTINCT ta.bid, 
                tb.bid 
FROM   table_a AS ta 
       JOIN table_b AS tb using (uid) 
WHERE  uid = 123; 

我明显得到了错误的答案。为什么它会得到150多个结果而不是30个?

6 个答案:

答案 0 :(得分:2)

SELECT ta.bid, 
       tb.bid 
FROM   table_a AS ta, 
       table_b AS tb 
WHERE  ta.uid = tb.uid 
       AND ta.uid = 123 
GROUP  BY ta.bid, 
          tb.bid 

第二种方法是

SELECT ta.bid, 
       tb.bid 
FROM   table_a AS ta 
       INNER JOIN table_b AS tb 
               ON ( ta.uid = tb.uid ) 
                  AND ( ta.uid = 123 ) 

答案 1 :(得分:2)

试试这个

SELECT DISTINCT bid FROM TABLE_A WHERE uid = 123
UNION 
SELECT DISTINCT bid FROM TABLE_B WHERE uid = 123

SELECT DISTINCT bid 
FROM (SELECT bid FROM TABLE_A WHERE uid = 123
      UNION 
      SELECT bid FROM TABLE_B WHERE uid = 123
     ) AS A

答案 2 :(得分:1)

试试这个

select tb1.bid, tb2.bid from TABLE_A  AS tb1  , TABLE_B  AS tb2 
where tb1.bid = tb2.bid 
AND tb1.bid = 123
group by tb1.bid

答案 3 :(得分:1)

您需要进行联合,过滤剩余的结果

SELECT bid 
FROM   table_a 
WHERE  uid = 123 
UNION 
SELECT bid 
FROM   table_b 
WHERE  uid = 123 

这是帮助您想象结果的小提琴:http://sqlfiddle.com/#!2/27eea5/4

答案 4 :(得分:1)

USE UNION 它用于组合两个或多个SELECT语句的结果。

SELECT  bid FROM TABLE_A WHERE uid = 123
UNION 
SELECT  bid FROM TABLE_B WHERE uid = 123

答案 5 :(得分:0)

试试这个..

SELECT DISTINCT bid 
FROM   (SELECT bid 
        FROM   table_a 
        WHERE  uid = 123 
        UNION 
        SELECT bid 
        FROM   table_b 
        WHERE  uid = 123) AS temp;