2014-10-02 70 views
-2

我的數據庫中有下一個表。我需要確定用戶購買的所有圖書以及購買特定圖書的所有用戶。SQL查詢無法正確運行

http://i.imgur.com/IPb0bmi.png

這些都是我的SQL請求,但不順心的事:

select * 
from Livres 
where idCatalogue_fk in (
    select idCatalogue_fk 
    from ProduitsEtCommandes 
    where idCommande_fk in (
     select idCommande_fk 
     from CommandesEtUtilisateurs 
     where idUtilisateur_fk=1 
    ) 
); 


select * 
from Utilisateurs 
where idUtilisateur in (
    select idUtilisateur_fk 
    from CommandesEtUtilisateurs 
    where idCommande_fk in (
     select idCommande_fk 
     from Catalogue 
     where idCatalogue in (
      Select idLivre 
      from Livres 
      where idCatalogue=1 
      and title='Poezii' 
     ) 
    ) 
); 
+0

這些是嵌套'SELECT'語句。你最好用'JOIN's – ne1410s 2014-10-02 17:24:44

+1

什麼地方出錯?你能提供樣本數據和期望的輸出嗎?編輯您的問題以包括其中的一些細節。 – 2014-10-02 17:30:42

+0

你是什麼意思「出現問題」? – Kritner 2014-10-02 17:31:06

回答

2

我不知道法國... 有可能是拼寫錯誤與表和列名。 ..使用where爲特定用戶或書籍添加過濾器。

編輯

你能不能做到這一點? (如果這是家庭作業,這不是一個數據庫模型的一個很好的例子......順便說一句)

select * from livres where idCatalogue_fk in ( 
    select idCatalogue_fk from produitsEtCommandes where idUtilisasteur_fk=1 
); 


-- note the misspelling comment i made up top... the ID in productsNCommands 
select * from utilisateurs where idUtilisateurs in ( 
     select idUtilisasteur_fk from produitsEtCommandes where idCatalogue_fk in (
           select idCatalogue_fk from livres where idLivre=1 
          ) 
    ); 

基本上......根據數據模型,您需要:

  • 加入裏弗
  • 加入目錄
  • 加入produitsEtCommandes
  • 加入commandes

這將給你每個livre-commande協會。然後根據您的需求進行過濾。

找到與用戶Kim相關聯的所有書籍(假設這個名字只有一個用戶):

select * 
from  livres 
     join catalogue on livres.idCatalogue_fk=catalogue.idCatalogue 
     join produitsEtCommandes on produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue 
     join commandes on commandes.idCommande=produitsEtCommandes.idCommande_fk 
where commandes.nomClient = 'Kim' 

左右....你能做到這一點,那麼......?

select * from livres where idLivre in ( 
      select distinct idLivre 
      from  livres 
         join catalogue on livres.idCatalogue_fk=catalogue.idCatalogue 
         join produitsEtCommandes on produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue 
      where idCommandes_fk=1) 

或....(那麼難看)

select * 
from  livres, catalogue, produitsEtCommandes, commandes 
where livres.idCatalogue_fk=catalogue.idCatalogue and 
     produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue and 
     commandes.idCommande=produitsEtCommandes.idCommande_fk and 
     livres.title = 'Brave New World' 

哦,不一沒有....

select * from livres where idCatalogue_fk in (
     select distinct idCatalogue from catalogue where idCatalogue in (
         (select distinct idCatalogue_fk from produitsEtCommandes where idCommandes_fk=1) 
       ) 
    ) 
+0

問題是我不允許使用內部連接,只需選擇 – Nicolae 2014-10-02 17:36:18

+0

好吧....爲什麼這是完全一樣的? – 2014-10-02 17:36:39

+0

@ gloomy.penguin也許是作業:P – Kritner 2014-10-02 17:39:26