I'm new with SQL and just had my first assignment.
I have the following requirements: Given is a database of two tables. The first one contains information about the user, like a unique ID per user, the phone number and the city. ID and phone number consist only of numeric digits. The second table contains data about so called „credits“, which a user can own. Again there is a column for the unique user ID, but also the number, the date and the type of credits. A user can have none, one or several entries in the credit table.
I'm still now sure if I got right the part where a user can have none, one or several entries in the credit table. I created these two tables:
CREATE table user
(
user_id INT NOT NULL UNIQUE AUTO_INCREMENT,
user_phone_number INT NOT NULL,
user_city VARCHAR(32) NOT NULL,
PRIMARY KEY (user_id)
);
CREATE table credit
(
credit_user_id INT FOREIGN KEY (user_id),
credit_date date,
credit_number double,
credit_type char(10),
CONSTRAINT chk_type CHECK (credit_type in ('None','A','B','C')),
);
After creating this, I was asked the following questions:
a) The phone number of all users, who own credits of type „A“
SELECT user_phone_number
FROM user, credit
WHERE credit_type = 'A';
b) Like a), but additionally the credit_number of the credits is smaller than 2 or greater than 4
SELECT user_phone_number
FROM user, credit
WHERE (credit_type ='A')
AND (credit_number < 2 OR credit_number > 4);
C) Like a), but additionally the users also own credits of at least one other type.
SELECT user_phone_number
FROM user, credit
WHERE credit_type = 'A'
AND (
SELECT DISTINCT c1.credit_type FROM credit AS c1
JOIN credit a1 ON (c1.credit_type=a1.credit_type)
JOIN credit a2 ON (c1.credit_type=a2.credit_type)
WHERE a2.credit_type<>a1.credit_type);
My problem is that I can't make letter C work, even if both selects seem to work separately. Any ideas or suggestions would be appreciated, thank you!