以下mysql查询
SELECT *
FROM alerts_list l, alerts_data d, alerts_push_data p
WHERE p.push_data_hash = d.alerts_data_hash
AND p.push_data_alert_id = l.alerts_id
AND d.alerts_data_id = l.alerts_id
AND d.alerts_data_hash = 'JiaYRSVNZxgE'
通过连接三个表来显示JiaYRSVNZxgE
的结果。
以下是我使用的表格以及我想要在它们之间连接的列:
表alerts_list
专栏:alerts_id
表alerts_push_data
专栏:push_data_alert_id
专栏:push_data_hash
表alerts_data
专栏:alerts_data_id
专栏:alerts_data_hash
我想要达到的目标是:
将push_data_alert_id
与alerts_id
将alerts_data_id
与alerts_id
但仅显示alerts_data_hash
和push_data_hash
为"abcdef"
的结果
不幸的是,我的查询结果没有找到结果,但实际上有结果。 我做错了什么?
答案 0 :(得分:2)
您可以使用MySQL JOINS来轻松地执行该操作:
<?php
// USING NORMAL JOIN:
// WE NOW ADD AN EXTRA LAYER (THE VARIABLE $fldVal)
// IN THE CASE THAT YOUR VALUE ('JiaYRSVNZxgE') IS DYNAMIC...
$fldVal = 'JiaYRSVNZxgE';
$sql = "SELECT DISTINCT *
FROM alerts_list l
JOIN alerts_data d ON d.alerts_data_id=l.alerts_id
JOIN alerts_push_data p ON p.push_data_alert_id=l.alerts_id
WHERE d.alerts_data_hash='" . $fldVal . "'";
// USING LEFT JOIN:
// WE NOW ADD AN EXTRA LAYER (THE VARIABLE $fldVal)
// IN THE CASE THAT YOUR VALUE ('JiaYRSVNZxgE') IS DYNAMIC...
$fldVal = 'JiaYRSVNZxgE';
$sql = "SELECT DISTINCT *
FROM alerts_list l
LEFT JOIN alerts_data d ON d.alerts_data_id=l.alerts_id
LEFT JOIN alerts_push_data p ON p.push_data_alert_id=l.alerts_id
WHERE d.alerts_data_hash='" . $fldVal . "'";
// USING INNER JOIN:
// WE NOW ADD AN EXTRA LAYER (THE VARIABLE $fldVal)
// IN THE CASE THAT YOUR VALUE ('JiaYRSVNZxgE') IS DYNAMIC...
$fldVal = 'JiaYRSVNZxgE';
$sql = "SELECT DISTINCT *
FROM alerts_list l
INNER JOIN alerts_data d ON d.alerts_data_id=l.alerts_id
INNER JOIN alerts_push_data p ON p.push_data_alert_id=l.alerts_id
WHERE d.alerts_data_hash='" . $fldVal . "'";
::并按照CLAUSE ::
进行新的更新 <?php
// WE NOW ADD AN EXTRA LAYER (THE VARIABLE $fldVal)
// IN THE CASE THAT YOUR VALUE ('JiaYRSVNZxgE') IS DYNAMIC...
$fldVal = 'JiaYRSVNZxgE';
$sql2 = "SELECT DISTINCT *
FROM alerts_list AS A_LIST
LEFT JOIN alerts_push_data A_PUSH ON A_PUSH.push_data_alert_id=A_LIST.alerts_id
LEFT JOIN alerts_data A_DATA ON A_DATA.alerts_data_hash=A_PUSH.push_data_hash
WHERE A_DATA.alerts_data_hash='" . $fldVal . "'
GROUP BY A_LIST.alerts_id";
TEST-CASE QUERY
SELECT DISTINCT *
FROM alerts_list AS A_LIST
LEFT JOIN alerts_push_data A_PUSH ON A_PUSH.push_data_alert_id=A_LIST.alerts_id
LEFT JOIN alerts_data A_DATA ON A_DATA.alerts_data_hash=A_PUSH.push_data_hash
WHERE A_DATA.alerts_data_hash='iSg2loGJDaWs'
GROUP BY A_LIST.alerts_id
<强> RESULT 强>
这些是可以预料的,因为除了 alerts_list 有10行之外,我在所有其他表中只模拟了2行。
表:alerts_list