Integration of MYSQL

Source: Internet
Author: User

Yesterday I met a seemingly simple SQL statement (many-to-many relationship )[Mysql-based].

I asked all the computer professionals I know and a number of graduate students.
Then I added 12 technical groups, three of which were discussed for more than two hours.

I think this problem is not difficult and there are feasible solutions! The requirement is as follows:

Database Structure:
User_name product_id
1
2 B
1 B
3 C
4 C
1 C

Requirements:Which users have bought A, C, and D at the same time? (Or, what are the users who buy A, C, and D at the same time ?)
A, C, and D are input temporarily by the user. They are determined each time, but not fixed.

I got up this morning and didn't think of a solution, so I decidedModify requirements.

At this moment, I suddenly remembered, a friend of mine.

Http://t.qq.com/chuwey. SQL is directly written for the database of the bank.

I called and talked about my requirements. After rendering this question, many people did not make it, which is difficult. In addition, many people suggested using regular expressions or temporary tables.
He pondered for five seconds and said with a doubt: "You don't need to be so complicated. Your demand is very simple. It is a simple problem of intersection, or within a table, one SQL statement can solve the problem. In this way, I will send you a text message now ."

So we have the following SQL.

Mark the text as follows:

SELECT user_name
FROM product_buy
Where product_id in (13834720379,222 2485585)
Group by user_name
Having count (distinct product_id) = 2;

Later, Weibo friends http://t.qq.com/jcifox also sent a way of thinking, share it.

This entry is published by Prince Mo

Directory of the front-end. Add a fixed link to favorites. Http://julying.com/blog/mysql-and-problem-sets/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.