从两个mysql表中检索数据并返回单个结果

时间:2013-01-10 07:42:31

标签: mysql select join union

我有两个mysql表,例如

countriesRanking table

country, clicks
-------  -----
0         657  
1         3300
2         9050

clickTable表

id, name,    clicks,  deviceid, country
-- ------    ------   --------  -------
0   player1  33       uniqueid1  0
1   player2  665      uniqueid2  2 
2   player3  88       uniqueid3  18
3   player4  5000     uniqueid4  2

我想从countriesRanking表中检索指定国家/地区的点击值,以及clickTable中指定了deviceid的点击值。

这样的东西
SELECT clicks FROM clicksTable WHERE deviceid='$deviceid' UNION SELECT clicks FROM countriesRanking WHERE country='$country'

因此,如果deviceid是uniqueid4且country是2,则返回

5000, 9050

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ct.clicks fromClicks, cr.clicks fromCountry
FROM clicksTable ct 
LEFT JOIN countriesRanking cr ON ct.country = cr.country 
WHERE ct.deviceid='uniqueid4' AND ct.country = 2;

点击此链接SQL FIDDLE DEMO

<强>输出

| FROMCLICKS | FROMCOUNTRY |
----------------------------
|       5000 |        9050 |

答案 1 :(得分:0)

试试这个

SELECT clicks FROM clicksTable ct
join countriesRanking cr on cr.country=ct.country

WHERE deviceid='$deviceid' and cr.country='$country'

答案 2 :(得分:0)

  

我想从countriesRanking表中检索点击值   指定了country并且clickTable中的click值在哪里   指定了deviceid。

像这样:

SELECT clicks 
FROM clicksTable 
WHERE deviceid = 'uniqueid4' 
UNION ALL
SELECT clicks 
FROM countriesRanking 
WHERE country = 2;

SQL Fiddle Demo

这会给你:

| CLICKS |
----------
|   5000 |
|   9050 |

答案 3 :(得分:0)

我认为您的查询是正确的,但您拼错了表名clickTable。您改为编写了clicksTable