Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching from multiple relationships

I have a "posts" table. Each post record can have one or more tags. If I store the tags into a single column, as a comma delimited string, I can easily find the posts that have tag "Abc" and tag "Def", or even do partial matching.

I'm using sqlite and a "FTS" table with this method and it works fine, but someone told me that it's a bad practice and I should store the tags in a different table and use JOINs. If I store the tags in a different table and create a relationship between these 2 tables, how do I find posts with both tag "Abc" and tag "Def" in a single query? Is it possible?

like image 434
Elfy Avatar asked Mar 05 '15 12:03

Elfy


People also ask

Why would you use Neo4j match?

The MATCH clause allows you to specify the patterns Neo4j will search for in the database. This is the primary way of getting data into the current set of bindings. It is worth reading up more on the specification of the patterns themselves in Patterns.

How many nodes can a single relationship connect?

A relationship connects two nodes — a start node and an end node. Just like nodes, relationships can have properties.

When must you use a variable in a simple match clause?

If you want to return the relationship between two nodes or a property of the relationship, a variable is required. A directed or undirected relationship can be used.

How do you write a Cypher query?

Cypher uses an ASCII-art type of syntax where (nodes)-[:ARE_CONNECTED_TO]->(otherNodes) using rounded brackets for circular (nodes) , and -[:ARROWS]-> for relationships. When you write a query, you draw a graph pattern through your data.


1 Answers

That is indeed bad design practice.

You will get slow performance since you need to do string operations on the column value to seperate the tags. So indexes can't be used. And it is against the normalization rules of database design.

A better design would be

tags table
----------
id
name


posts table
-----------
id
title
body
...


post_tags table
---------------
post_id
tag_id

To get all posts have both tags do

select p.id, p.title, p.body
from posts p
join post_tags pt on pt.post_id = p.id
join tags t on pt.tag_id = t.id
where t.name in ('abc','def')
group by p.id, p.title, p.body
having count(distinct t.id) = 2
like image 102
juergen d Avatar answered Nov 06 '22 17:11

juergen d