1. 程式人生 > >php中mysql一條sql語句查詢出所有符合條件的資料,該怎麼寫?

php中mysql一條sql語句查詢出所有符合條件的資料,該怎麼寫?

假如一個表裡有個classid欄位是類別的id,我想用一條sql語句查出classid=5的所有資料的id該怎麼查呢?正常是要迴圈,放到數組裡的吧

如圖,我想查詢classid=2的對應所有id,用一條sql語句

不知道你的a,b兩表有沒有關聯,假定沒有關聯
select count(1)
from 
(
select id
from a 
where id>5
union all
select id 
from b 
where id>5
)
sql多表關聯查詢跟條件查詢大同小異,主要是要知道表與表之前的關係很重要;

  舉例說明:(某資料庫中有3張表分別為:userinfo,dep,sex)

  userinfo(使用者資訊表)表中有三個欄位分別為:user_di(使用者編號),user_name(使用者姓名),user_dep(使用者部門) 。(關係說明:userinfo表中的user_dep欄位和dep表中的dep_id欄位為主外來鍵關係,userinfo表中的user_sex欄位和sex表中的sex_id欄位為主外來鍵關係)

dep(部門表)表中有兩個欄位分別為:dep_id(部門編號),dep_name(部門名稱)。(主鍵說明:dep_id為主鍵)

sex(性別表)表中有兩個欄位分別為:sex_id(性別編號),sex_name(性別名稱)。(主鍵說明:sex_id為主鍵)

‍‍一,兩張表關鍵查詢

1、在userinfo(使用者資訊表)中顯示每一個使用者屬於哪一個部門。sql語句為:

select userinfo.user_di,userinfo.user_name,dep_name from userinfo,dep where userinfo.user_dep=dep.dep_id

2、在userinfo(使用者資訊表)中顯示每一個使用者的性別。sql語句為:

select userinfo.user_di,userinfo.user_name,sex.sex_name from userinfo,sex where userinfo.user_sex=sex.sex_id

二、多張表關鍵查詢

    最初查詢出來的userinfo(使用者資訊表)表中部門和性別都是以數字顯示出來的,如果要想在一張表中將部門和性別都用漢字顯示出來,需要將三張表同時關聯查詢才能實現。

 sql語句為:

select userinfo.user_di,userinfo.user_name,dep.dep_name,sex.sex_name from userinfo,dep,sex where userinfo.user_dep=dep.dep_id and userinfo.user_sex=sex.sex_id

(多個條件用and關聯)