Advertisement
cdsatrian

test query

Aug 30th, 2013
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.39 KB | None | 0 0
  1. DROP TABLE IF EXISTS tabel1;
  2. CREATE TABLE IF NOT EXISTS tabel1 (
  3. id TINYINT(2) unsigned NOT NULL,
  4. nama VARCHAR(10)NOT NULL
  5. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
  6. INSERT INTO tabel1
  7. VALUES
  8. (1,'data 1'),
  9. (2,'data 2'),
  10. (3,'data 3'),
  11. (4,'data 4'),
  12. (5,'data 5'),
  13. (6,'data 6'),
  14. (7,'data 7'),
  15. (8,'data 8'),
  16. (9,'data 9'),
  17. (10,'data 10');
  18.  
  19. DROP TABLE IF EXISTS tabel2;
  20. CREATE TABLE IF NOT EXISTS tabel2 (
  21. tabel1_id TINYINT(2) unsigned NOT NULL,
  22. cat_id TINYINT(2)unsigned NOT NULL
  23. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
  24.  
  25. INSERT INTO tabel2
  26. VALUES
  27. (1,1),
  28. (1,2),
  29. (1,3),
  30. (2,1),
  31. (2,2),
  32. (3,1),
  33. (4,1),
  34. (4,3),
  35. (5,2),
  36. (6,2);
  37.  
  38. DROP TABLE IF EXISTS cat;
  39. CREATE TABLE IF NOT EXISTS cat (
  40. id TINYINT(2) unsigned NOT NULL,
  41. nama VARCHAR(10)NOT NULL
  42. ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
  43.  
  44. INSERT INTO tabel2
  45. VALUES
  46. (1,'cat 1'),
  47. (2,'cat 2'),
  48. (3,'cat 3');
  49.  
  50. -- #1 QUERY
  51. SELECT
  52.   a.id,
  53.   a.nama
  54. FROM
  55.   tabel1 a
  56.   JOIN tabel2 b ON a.id = b.tabel1_id
  57. WHERE
  58.   b.cat_id IN (1,2)
  59. GROUP BY
  60.   a.id
  61. HAVING
  62.   COUNT(a.id)=2
  63.  
  64. -- #2 QUERY
  65. SELECT
  66.   b.id,
  67.   b.nama
  68. FROM
  69.   tabel2 a
  70.   JOIN tabel1 b ON b.id=a.tabel1_id
  71. GROUP BY
  72.   a.tabel1_id
  73. HAVING
  74.   SUM(IF(a.cat_id=1,1,0)) * SUM(IF(a.cat_id=2,1,0))=1
  75.  
  76. -- #3 QUERY
  77. SELECT
  78.   b.id,
  79.   b.nama
  80. FROM
  81.   tabel2 a
  82.   JOIN tabel1 b ON b.id=a.tabel1_id
  83.   JOIN tabel2 c ON a.tabel1_id=c.tabel1_id
  84.     AND a.cat_id=1
  85.     AND c.cat_id=2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement