sql - запрос соединения 2 таблицы с 1 таблицей - PullRequest
0 голосов
/ 06 апреля 2020

извините, если заголовок не связан с моим вопросом. Я не знаю, какой правильный заголовок для этого.

Итак, у меня есть 5 таблиц, чтобы показать пользователю соответствующий контент

  1. Контент (id, content, et c ..) Data related content
  2. ContentCategory (id, contentId, followCategoryId) Data related content's categories
  3. ContentPublisher (id, contentId, followPublisherId) Data related content's publishers
  4. FollowCategory ( id, categoryId, userId (подписчики), et c ..) Data related user's followed categories
  5. FollowPublisher (id, publisherId, userId (подписчики), et c ..) Data related user's followed publishers

Как показать содержимое на основе пользовательских категорий и подписчиков, и, если возможно, как отличить содержание от отношения на followCategory или followPublisher

Например: ниже мой запрос на показ контента на основе пользователя FollowPublisher, cmiiw

SELECT content.id, content.description, ...etc 
FROM followPublisher
LEFT JOIN publisher ON followPublisher.publisherId = publisher.id
LEFT JOIN contentPublisher ON publisher.id = contentPublisher.publisherId
RIGHT JOIN content ON contentPublisher.contentId = content.id
    WHERE followPublisher.userId = 8
ORDER BY content.created desc;

и ниже - мой запрос на показ контента на основе пользователя followCategory

SELECT content.id, content.description, ...etc 
FROM followCategory
LEFT JOIN category ON followCategory.categoryId = category.id
LEFT JOIN contentCategory ON category.id = contentCategory.categoryId
RIGHT JOIN content ON contentCategory.contentId = content.id
    WHERE followCategory.userId = 8
ORDER BY content.created desc;

Как объединить эти 2 запроса в показывать контент на основе подписки пользователя редактировать категории и издателей сразу или есть ли лучший способ вместо объединения запросов?

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020

Использование Union

с 2 условиями

  • Не использовать никакие связанные таблицы (не знаю, как это сказать) в order by вместо переименования это с использованием as. В моем случае значение order by content.created должно быть изменено на content.created as contentCreated, а затем мы можем использовать его на order by.

  • Добавить столбец значений по умолчанию, чтобы указать, откуда поступают данные (в в этом случае, будь то followPublisher или followCategory)

запрос:

SELECT content.id, content.description, content.created as contentCreated ...etc, 'publisher' as type
FROM followPublisher
LEFT JOIN publisher ON followPublisher.publisherId = publisher.id
LEFT JOIN contentPublisher ON publisher.id = contentPublisher.publisherId
RIGHT JOIN content ON contentPublisher.contentId = content.id
    WHERE followPublisher.userId = 8
UNION
SELECT content.id, content.description, content.created as contentCreated ...etc, 'category' as type
FROM followCategory
LEFT JOIN category ON followCategory.categoryId = category.id
LEFT JOIN contentCategory ON category.id = contentCategory.categoryId
RIGHT JOIN content ON contentCategory.contentId = content.id
    WHERE followCategory.userId = 8
ORDER BY contentCreated desc;
0 голосов
/ 06 апреля 2020

Я думаю, вы хотите следующее:

select content.* from content
LEFT JOIN contentPublisher ON content.id = contentPublisher.contentId 
LEFT JOIN Publisher ON contentPublisher.publisherId = publisher.id 
LEFT JOIN followPublisher ON publisher.id = followPublisher.publisherId
LEFT JOIN contentCategory ON content.id = contentCategory.contentId 
LEFT JOIN category ON contentCategory.categoryId = category.id 
LEFT JOIN followcategory ON category.id = followcategory.categoryId
where followPublisher.userId = 8 or followCategory.userId = 8
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...