1
我有兩個獨立的SQL查詢,如果可能的話,我想合併成一個SQL查詢。兩個SQL查詢的組合
查詢#1產生隨機順序表中的所有條目
查詢#2將事後檢查結果是否可用於
在一個單一的步驟,直接在SQL我怎樣才能做到這一點?
代碼:
// start with a query for all of the photos, returned in random order
$query = "
SELECT DISTINCT m.mediaID
, m.description
, m.path
, m.alwayson
, m.usecollfolder
, m.mediatypeID
FROM $media_table m
WHERE m.mediatypeID = 'photos'
ORDER BY RAND();
";
$result = mysql_query($query) or die ("$text[cannotexecutequery]: $query");
while($imgrow = mysql_fetch_assoc($result)) {
// if the picture is alwayson or we are allowing living to be displayed,
// we don't need to bother
// with any further checking
if ($imgrow[alwayson] || $allow_living_db) {
break;
// otherwise, let's check for living
} else {
// this query will return rows of personIDs on the photo that are living
$query = "
SELECT l.personID
FROM $medialinks_table l
JOIN $people_table p ON l.personID = p.personID
WHERE l.mediaID = $imgrow[mediaID]
AND p.living = 1
";
$presult = mysql_query($query) or die ("$text[cannotexecutequery]: $query");
$rows = mysql_num_rows($presult);
mysql_free_result($presult);
// if no rows are returned, there are no living on the photo, so let's display it
if ($rows == 0) {
break;
}
}
爲什麼不是第一個查詢的WHERE的 '始終'?之後,這是一個簡單的JOIN。 – user2864740
請閱讀https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Michas
謝謝,Michas。我正在轉換到WordPress中的$ wpdb數據庫類。這就是爲什麼我查看代碼的原因。 – mzurhorst