Mysql
 sql >> база данни >  >> RDS >> Mysql

SQL:цикъл през същата таблица

нещо като това? FIDDLE за справка

SELECT project_id,project_name,parent_id,recycle_bin,creater_id
FROM projectdetails AS pd1
JOIN(
    SELECT parent_id FROM projectdetails as pd
    WHERE pd.parent_id > 0 AND pd.recycle_bin > 1
) AS t ON t.parent_id = pd1.project_id

с нови данни.. NEW_FIDDLE

SELECT 
  if(pd1.recycle_bin >1, pd1.project_id, t.project_id) AS project_id,
  if(pd1.recycle_bin >1, pd1.project_name, t.project_name) AS project_name,
  if(pd1.recycle_bin >1, pd1.parent_id, t.parent_id) AS parent_id,
  if(pd1.recycle_bin >1, pd1.recycle_bin, t.recycle_bin) AS recycle_bin,
  if(pd1.recycle_bin >1, pd1.creater_id, t.creater_id) AS creater_id
FROM projectdetails AS pd1
JOIN(
  SELECT * FROM projectdetails AS pd
  WHERE pd.parent_id > 0 
    AND pd.recycle_bin > 1
) AS t ON t.parent_id = pd1.project_id
GROUP BY project_id

без да използвате LAST_FIDDLE на IF

SELECT 
   pd1.project_id,
   pd1.project_name,
   pd1.parent_id,
   pd1.recycle_bin,
   pd1.creater_id
FROM projectdetails AS pd1
WHERE NOT EXISTS(
  SELECT pd.recycle_bin FROM projectdetails as pd
  WHERE pd1.parent_id = pd.project_id 
    AND pd.recycle_bin > 1
) AND pd1.creater_id = 7923 and pd1.recycle_bin > 1
GROUP BY pd1.project_id;


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. как да изберете 2 таблици като тази

  2. Повишаване на нивото на управление на MySQL, MariaDB, PostgreSQL и MongoDB

  3. Rails избират произволен запис

  4. как да получите текст от pdf файл и да го запишете в DB

  5. Неразумно ли е да присвоявам MySQL база данни на всеки потребител на моя сайт?