1

I have two tables that have foreign keys to each other's primary key. This DB is in French. I will translate the two tables that I want to you to understand.

  • Atelier Cuisine ==> Kitchen
  • Cuisinier == > Cooking chef

So in this picture we see that in the Kitchen table we have a PK referenced by the FK from the Cooking chef table; in the Cooking chef table we have a PK referenced by the FK from the Kitchen table. So I am confused. I don't understand this kind of relationship between these tables.

And I hope to check my query that I did to create these two tables if its correct

CREATE TABLE [ATELIER CUISINE] ( 

NumCuisine INT NOT NULL PRIMARY KEY,
TelCuisine VARCHAR(50) NOT NULL
)

CREATE TABLE CUISINIER (

NumCuisinier  INT NOT NULL PRIMARY KEY,
NomCuis  VARCHAR(50) NOT NULL,
DateEmb DATE NOT NULL,
NumCuisine INT NOT NULL CONSTRAINT FK_CUISINIER_NumCuisine FOREIGN KEY REFERENCES [ATELIER CUISINE](NumCuisine)

See the Image here:
Relationship model of the restaurant database

See the Image here:
Example records for some tables

philipxy
  • 14,867
  • 6
  • 39
  • 83
med
  • 68
  • 1
  • 10
  • Probably this FK is allowed NULL values. So you can generate one entry first, and them link them. But this still not making any sense. – MarceloBarbosa Feb 12 '17 at 15:57
  • 1. What does "kind of relationship between tables" mean? You already know about the PKs & FKs. 2. Your comments ask for a query. Edit that into your question. But, *query for what*? (And what have you tried?) – philipxy Feb 14 '17 at 15:30
  • 1. Again, please use cut & paste the text in your images into your question. Use code format for tables. We can't cut and paste from images. If you can't either, use online OCR, then cut & paste. 2. What query? There is still no query in your question, or description of a query. Do you mean the *table definitions*?? Please edit your question to be clear. Please edit your question so that you are *asking one question*. Right now your title is *one* (*unclear*) question, and the post body says what you *hope*, but doesn't *ask a question*, and if it *did*, it would be a *second* question. – philipxy Feb 15 '17 at 06:03

4 Answers4

0

What you are seeing here is most probably the most important child pattern.

I would assume that we need to start from the standard parent-child relationship of "one kitchen employs one-or-more chefs". So we would have a foreign key in the cuisinier / chef table that contains the ID of the atelier_cuisine / kitchen where the cuisinierin question works.

But for some reason, the kitchen must be able to point at the most important cook/chef working there. Only that numCuisinier or chefID / cookID is a poor naming of that foreign key column, as it misleads, just as it mislead us in your example. If you gave it a name like numCuisinierChef or "chef/cook in chief ID", the column name would be self-explanatory.

But, the way the columns were named here, it could also be just the other way around: a chef/cook works in one or more kitchens, but one kitchen is his or her most important employer.

Without a documentation or comments in the data model, you're fried, really ...

Hope this helps rather than confuses - as the data model and the naming does ...

Maybe one clue. MarceloBarbosa actually inspired me to that: If , in atelier_cuisine , numCuisinier is null-able, and , in cuisinier, numCuisine is NOT NULL, then atelier_cuisine is the parent, and cuisinier is the child, and vice-versa.

Marco the Sane

marcothesane
  • 6,192
  • 1
  • 11
  • 21
  • Thank you so much for your anwser You are right in the documentation they didnt put comments to explain data model clearly but I need the implementation query how can I write the query of these two tables in sql server ? – med Feb 12 '17 at 19:36
  • @mohammedaamoum What do you mean, "the query of these two tables"? There is no one query. The query you write depends on what the tables mean and what the query means. What do you want to know about the application, and what do the tables tell you about the application? How or why would you possibly write a query without knowing these things? PS A base table holds rows of values related in some way, ie that participate in some relationship. So does a query. The query's relationship is determined by the SQL and vice versa, in terms of base table relationships & values. FKs are irrelevant. – philipxy Feb 13 '17 at 15:32
0

Tables (base and query results) represent application relationships.

From (an earlier version of) this answer:

For every base table, the DBA gives a predicate--a natural language fill-in-the-(named-)blanks statement template parameterized by column names.

-- chef with id NUMCUISINIER has name NOMCUIS and ...
CUISINIER(NumCuisinier, NomCuis, ...)

A base table holds the rows that, using its columns' values to fill in the (named) blanks, make a true statement aka proposition.

CUISINIER
NumCuisinier | NomCuis | ...
----------------------------
1            | DURAND  | ...  -- chef with id 1 has name 'DURAND' and ...
...

-- AND for every absent row (NUMCUISINIER, NOMCUIS, ...),
    NOT (chef with id NUMCUISINIER has name NOMCUIS and ...)

Each SQL expression/clause transforms an old table value to a new value holding the rows that make a true statement from some new predicate that can be expressed in terms of the original's predicate.

The predicate of R JOIN S is the predicate of R ANDed with the predicate of S. The predicate of R ON/WHEREcondition is the predicate of R ANDed with condition.

/* rows where
     chef with id c.NUMCUISINIER has name c.NOMCUIS and ...
AND kitchen with id a.NUMCUISINE ...
AND c.NUMCUISINE = a.NUMCUISINE
*/
CUISINIER c join ATELIER_CUISINE a on c.NumCuisine = a.NumCuisine

So we query by writing an SQL expression whose associated predicate characterizes the application relationship (aka association) whose rows we want.

FKs (foreign keys) are not relationships.

FK constraints are called relationships by some people, but they are not. They are facts.

A FK of a table is a set of columns. "FK" is also used to mean an associated constraint that we have when we have a FK. Which like every constraint is a true statement in every database state. (Equivalently, every application situation.) A FK constraint says that values for certain columns in a certain table are also values for certain columns in a certain other table where they form a CK (candidate key). (Equivalently, it says that if some values/entities satisfy a certain application relationship then some of them plus some other values/entities satisfy a certain other application relationship where the values/entities form a CK.) A PK (primary keys) is just some CK that you decided to call PK.)

A FK constraint has a certain associated application relationship, but that's not what is meant when "relationship" is used for "FK (constraint)". ("FK" is also used to mean a subrow value for the columns of a FK, or a value in a row for the column of a one-column FK.)

You need to know what each table means.

Predicates must be supplied by the designer along with a schema. You need to find out what the tables mean. Then express your query predicate in terms of them. Then convert to SQL.

Sometimes we guess at the predicates more or less successfully via common sense and naming. FKs and other constraints can help with guessing.

Common sense, names, PKs (underlined?) and FKs ("#"?) suggest table meanings for you like:

-- chef with id NUMCUISINIER has name NOMCUIS and start date DATEEMB and works in kitchen with id NUMCUISINE
CUISINIER(NumCuisinier, NomCuis, NateEmb, NumCuisine)
-- kitchen with id NUMCUISINE has phone number TELCUISINE and chef with id NUMCUISINIER as head chef
ATELIER_CUISINE(NumCuisine, TelCuisine, NumCuisinier)

FKs are not needed to query

In the SQL query above the rows that make the predicate into a true proposition are always the rows returned. It doesn't matter how many rows there are per NumCuisiner or NumCuisine value (ie whether they are PKs) or whether a value must appear in another table (ie whether they are FKs). Or what any other constraint is.

We need to know the predicates to query. When we know them we don't need to know any constraints. We don't need to know FKs.

FKs, CKs, PKs, alternate keys and UNIQUE column sets (superkeys) are irrelevant to querying except that if you know something is a superkey because of one then you can write queries involving extracting a value from a one-row result. But you could have expressed the same result without extractions.

philipxy
  • 14,867
  • 6
  • 39
  • 83
0

IMHO, this "key exchange" is plainly wrong; from the sample data we may conjecture (but not for sure!) that the relationship between [ATELIER CUISINE] and [CUISINER] is one-to-many (CUISINIER table), in which case the [ATELIER CUSINE] should NOT have the NumCuisinier column, or otherwise NumCuisine is not a Primary Key (which, according to the data model, is)! So the data model is probably wrong.

My best bet for your query would be

SELECT B.*, A.TelCuisine
FROM [ATELIER CUISINE] A INNER JOIN CUISINIER B ON A.NumCuisine = B.NumCuisine

Unless of course NumCuisinier in [ATELIER CUISINIER] table is NOT a FK, as @marcothesane suggests and it has a completely different meaning, in which case it should be contained in the result set (but with a different alias):

SELECT B.*, A.TelCuisine, A.NumCuisinier as [HeadChef]
FROM [ATELIER CUISINE] A INNER JOIN CUISINIER B ON A.NumCuisine = B.NumCuisine
Giorgos Altanis
  • 2,742
  • 1
  • 13
  • 14
0

So you want to know how to query this.

As many said, it depends on what is needed.

And - philipxy - I can't regard a foreign key as a fact; you can't calculate the sum or the average or the standard deviation of foreign key values. And, for a Kimball-ian as me, facts are facts because you can do these things with them.

And a foreign key is the depiction at data definition language level of the relationships between the entities that are depicted by the tables. My point of view, at least. But, actually, who cares as long as it works - and as long as we don't create confusion.

Having said that:

If you need all kitchens' telephone numbers and their head cook's name:

SELECT
  telCuisine
, nomCuisinier
FROM atelier_cuisine
JOIN cuisinier USING(numCuisinier)
;

If you need all cooks (no matter if chief cook or anybody else) that you can reach with one phone number in one kitchen, you go:

SELECT
  nomCuisinier
FROM atelier_cuisine
JOIN cuisinier USING(numCuisine)
WHERE telCuisine = '+39 6 23 25 22 13';

If you want to know all phone numbers of the kitchens where Gaston works, you go:

    SELECT
      telCuisine
    FROM cuisinier
    JOIN atelier_cuisine USING(numCuisine)
    WHERE numCuisinier='Gaston'
;

I'm aware there is the possibility to use the ON clause for the joins, but I'm lazy and prefer the USING() clause ...

Other than that, I would not know what your question might be, really ...

marcothesane
  • 6,192
  • 1
  • 11
  • 21
  • This is becoming interesting - but it does not really fit into this specific question. To me, a primary key and a foreign key "value" is the way to depict a pointer in a relational database, period. It's usually an integer, but a SUM() or an AVG() on it, while it's possible, makes no sense. Facts are measures in a data warehouse, to me. And a fact tables contains foreign keys ("pointers" to dimension table entries) and measures - like sales_amount, quantity and such. A fact as you describe it, is a semantic value. The best primary key has no semantic value whatsoever and is a surrogate key. – marcothesane Feb 13 '17 at 22:56
  • Nevertheless, the table predicates are *necessary and sufficient* to query a warehouse or database. Just try to justify that some query you wrote returns the right rows. Or try to write your comment *clearly*. (No scare quotes, 'to me', 'depict', 'period, 'usually' or 'and such'. Define 'pointer' & 'FK' (you mean value or subrow in FK column(s)), 'fact' & 'measure' (you mean value), 'makes no sense' & being or having a 'semantic value'.) *You need to use the framework explained by my answer*. It's just the math/reasoning behind the relational model. And your (vague) counterclaims disappear. – philipxy Feb 14 '17 at 02:24
  • "Facts all come with points of view Facts don't do what I want them to" [Talking Heads - Crosseyed And Painless (Remain In Light - 1980)](https://www.youtube.com/watch?v=WaffRW3hgUY) – philipxy Feb 14 '17 at 02:43
  • No need to be harsh with each other, @philipxy. You are referring to relational algebra, which is all about relations (not relationships). This is indeed a sound mathematical framework invented 4 decades ago, unfortunately it is not being followed that close by the major DB vendors. BTW, a "fact" in relational algebra is exactly a tuple. A FK is used to achieve normalization. – Giorgos Altanis Feb 14 '17 at 07:11
  • On the other hand, @marcothesane says he is a Kimball fun. This can explain why he does not consider a physical key to be a good key, but this is not a model constraint, it is only for practical purposes (and this can be challenged). Even the Kimball model is relational though, but with a lower level of normalization. According to Kimball, a "fact" is a tuple in a relation playing a specific role (the fact table), not to be confused with a measure, which is a numeric field which can be added, averaged, and so on. – Giorgos Altanis Feb 14 '17 at 07:18
  • @GiorgosAltanis marcothesane & I have deleted a few comments about this so far. The answer & comments reminded me of a song by my favourite band that isn't the Clash & I hope that will be taken lightly. I don't know why you think I am being harsh. I am just (if you'll pardon me) stating the facts. Technical vague is bad. (Though ubiquitous.) Ah, yet *another* 'fact' value definition, thx, also for 'measure' values. Well, my answer *explains* what it means, namely the everyday, logic & relational meaning. PS The math explains the SQL & product semantics. It is relevant. – philipxy Feb 14 '17 at 07:42
  • Sorry if I was too judgemental, perhaps I misunderstood. In fact :-) I find the topic of this discussion very interesting and important: math is both relevant and necessary, I agree 100%, although too many colleagues seem to devalue theory. Take care! – Giorgos Altanis Feb 14 '17 at 08:11