比方說,我有三個表(MySQL),一個用於用戶,一個用於標記,最後一個用於加入它們(多對多關係):在一個查詢中獲取行及其外鍵行與許多查詢
create table user_tag(
user_id int unsigned not null,
tag_id int unsigned not null,
primary_key (user_id, tag_id)
);
我想從數據庫中獲取完整的用戶列表(或至少其中很多)以及他們關聯的標籤。我使用PHP作爲服務器語言。
所以我的問題是,是能夠更好地執行一個SQL查詢獲取所有的信息是這樣的:
select user.name, user.image, ..., tag.name from user, tag, user_tag
where user.user_id = user_tag.user_id and tag.tag_id = user_tag.tag_id;
或者是它更好地爲用戶執行一個第一查詢和事後獲取他們的標籤:
select user.name, user.image, ... from user;
,然後爲每個用戶:
select tag.name from tag, user_tag where tag.tag_id = user_tag.tag_id
and user_tag.user_id = $USERID;
我覺得第二是更好的選擇,但恐怕對數據庫的查詢可能太多(注意,這是一個通用的設計示例,但此模式可以在具有不同表格的數據庫中多次出現)。
哪個更好?優點和缺點?其他方法?
感謝
PS:請不要考慮SQL語法,我沒有檢查出來對一個真正的數據庫,它是唯一的設計問題,謝謝大家
可能重複[JOIN查詢vs多個查詢](http://stackoverflow.com/questions/1067016/join-queries-vs-multiple-queries) – ManseUK